package com.cy.store.service.impl;

import com.cy.store.entity.Address;
import com.cy.store.mapper.AddressMapper;
import com.cy.store.service.IAddressService;
import com.cy.store.service.IDistrictService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    IDistrictService districtService;

    @Value("${user.address.max-count}")
    Integer maxCount;

    /**
     * 往t_address 里加数据
     */
    public Integer addNewAddress(Integer uid, String username, Address address) {
        Integer count = addressMapper.countByUid(uid);
        System.out.println("uid为" + uid + "的地址有几个：" + count);

        if(count >= maxCount){
            throw new AddressCountLimitException("最多保留20个地址");
        }

        // 添加省市区
        String provinceName = districtService.getNameByCode(address.getProvinceCode());
        String cityName = districtService.getNameByCode(address.getCityCode());
        String areaName = districtService.getNameByCode(address.getAreaCode());
        address.setProvinceName(provinceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);


        // 往address里添加：uid、IsDefault
        address.setUid(uid);
        Integer IsDefault = count == 0 ? 1 : 0;     // 是否默认：0-不默认，1-默认
        address.setIsDefault(IsDefault);

        // 补全4项日志
        address.setCreatedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedUser(username);
        address.setModifiedTime(new Date());

        Integer rows = addressMapper.insert(address);
        if(rows != 1){
            throw new InsertException("添加地址时出现未知错误");
        }

        System.out.println("修改的行数：" + rows);

        return rows;
    }


    /**
     * 查询t_address里某个用的数据
     */
    @Override
    public List<Address> getByUid(Integer uid) {

        List<Address> list = addressMapper.findByUid(uid);
        for(Address address: list){
            address.setProvinceCode(null);

            address.setCityCode(null);
            address.setAreaCode(null);
            address.setTel(null);

            address.setIsDefault(null);
            address.setCreatedTime(null);
            address.setCreatedUser(null);

            address.setModifiedTime(null);
            address.setModifiedUser(null);

        }
        System.out.println(list);
        return list;
    }

    /**
     * 更新默认地址
     */
    @Override
    public void setDefault(Integer aid, Integer uid, String username) {

        // 查地址是否存在
        Address result = addressMapper.findByAid(aid);
        if(result == null){
            throw new AddressNullException("这个地址不存在");
        }

        // 查是否非法访问
        if(!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法访问");
        }

        // 将此用户的所有地址设为不默认
        Integer rows = addressMapper.updateNonDefault(uid);
        System.out.println("地址有几条：" + rows);
        if(rows<1){
            throw new UpdateException("原先没有地址");
        }

        // 修改所选地址为默认地址
        rows = addressMapper.updateByAid(aid, username, new Date());
        System.out.println("新默认地址有几条：" + rows);

        if(rows != 1){
            throw new UpdateException("更新失败");
        }

    }


    /**
     * 删除地址
     */
    @Override
    public void delete(Integer aid, Integer uid, String username) {

        Address address = addressMapper.findByAid(aid);
        if(address == null){
            throw new AddressNullException("地址不存在");
        }

        if(!address.getUid().equals(uid)){
            throw new AccessDeniedException("非法访问");
        }




        Integer rows = addressMapper.deleteByAid(aid);
        System.out.println("删除几条数据：" + rows);

        if(rows != 1){
            throw new DeleteException("删除出现错误");
        }

        Integer count = addressMapper.countByUid(uid);
        if(count == 0){
            return;
        }

        // 当把默认地址删除掉后，选择把最新添加的地址改为默认地址。
        if(address.getIsDefault() == 1){
            Address obj = addressMapper.findLastModified(uid);


            Integer rows2 = addressMapper.updateByAid(obj.getAid(), username, new Date());
            if(rows2 != 1){
                throw new UpdateException("更新地址时出现未知异常");
            }
            System.out.println("当把默认地址删除掉后，选择把最新添加的地址改为默认地址");



        }


    }

    /**
     * 更新地址
     */
    @Override
    public void update(Address address) {
        Integer rows = addressMapper.update(address);

        System.out.println("更新了几条地址：" + rows);
    }


    /**
     * 根据aid 查询某条数据是否存在
     * @param aid
     * @param uid
     * @return
     */
    @Override
    public Address getByAid(Integer aid, Integer uid) {
        Address address = addressMapper.findByAid(aid);
        if (address == null){
            throw new AddressNullException("这个地址不存在");
        }



        if(!address.getUid().equals(uid)){
            throw new AccessDeniedException("非法访问的异常");
        }

        address.setProvinceCode(null);
        address.setCityCode(null);
        address.setAreaCode(null);
        address.setCreatedUser(null);
        address.setModifiedUser(null);
        address.setCreatedTime(null);
        address.setModifiedTime(null);

        return address;
    }


}
